package quq.missq.activity;

import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.android.volley.VolleyError;
import com.android.volley.toolbox.ImageLoader;
import com.google.gson.Gson;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;

import quq.missq.BaseActivity;
import quq.missq.Constants;
import quq.missq.MLog;
import quq.missq.R;
import quq.missq.adapter.MyHomePagerAdapter;
import quq.missq.beans.MyInformationBean;
import quq.missq.beans.TopicBean;
import quq.missq.utils.BitmapUtils;
import quq.missq.utils.UserTools;
import quq.missq.utils.VolleyTool;
import quq.missq.views.LoadMoreListView;

/**
 * Created by River on 8/3/15.
 */
public class MyHomePageActivity extends BaseActivity implements VolleyTool.HTTPListener, LoadMoreListView.OnLoadMore {

    private LoadMoreListView mListView;
    private LinkedList<TopicBean.TopicResult> results;
    private MyHomePagerAdapter adapter;
    private int maxResults = 10;
    private int currentPage = 1;

    private MyInformationBean bean = null;

    private ImageView mAvatar;
    private TextView mUserName;
    private TextView mUserType;
    private TextView mLevel;
    private TextView mGuanzhuCount;
    private TextView mFensiCount;
    private TextView mTangguoCount;
    private ImageView mGender;
    private LinearLayout ll_empty;
    private LinearLayout llHeadBg;
    private ImageView mShow;
    private ImageView mAuth;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.my_homepage_activity);
        initView();
        initListener();
        bean = (MyInformationBean) getIntent().getExtras().getSerializable("bean");
        initCommentData();
    }

    private void initView() {
        mListView = (LoadMoreListView) findViewById(R.id.listView);
        mShow = (ImageView) findViewById(R.id.show);
    }

    private void initCommentData() {
        results = new LinkedList<>();
        adapter = new MyHomePagerAdapter(this);
        View view = getHeadView();
        mListView.addHeaderView(view);
        adapter.setData(results);
        mListView.setAdapter(adapter);
        loadCommentNetworkData();
    }


    private View getHeadView() {
        LayoutInflater inflater = LayoutInflater.from(this);
        View view = inflater.inflate(R.layout.my_information_head_layout, null);
        initHeadView(view);
        mUserName.setText(bean.getData().getNkname());
        if (bean.getData().getAuth() != 2) {
            mShow.setVisibility(View.GONE);
        }
        switch (bean.getData().getAuth()) {
            case 0:
                mUserType.setText("普通用户");
                mAuth.setVisibility(View.GONE);
                break;
            case 1:
                mUserType.setText("加V");
                mAuth.setVisibility(View.GONE);
                break;
            case 2:
                mUserType.setText("女神");
                mAuth.setVisibility(View.VISIBLE);
                break;
        }
        mLevel.setText("level " + bean.getData().getLevel());
        mGuanzhuCount.setText(bean.getData().getFollows() + "");
        mFensiCount.setText(bean.getData().getFans() + "");
        mTangguoCount.setText(bean.getData().getAccount().getAmountSweet() + "");
        String bgUrl = bean.getData().getBackground();
        if (bgUrl != null && !bgUrl.isEmpty()) {
            VolleyTool.getImageLoader().get(Constants.IMAGE_HOST + bgUrl, new ImageLoader.ImageListener() {
                @Override
                public void onResponse(ImageLoader.ImageContainer imageContainer, boolean b) {
                    if (imageContainer != null && imageContainer.getBitmap() != null) {
                        llHeadBg.setBackgroundDrawable(new BitmapDrawable(getResources(), imageContainer.getBitmap()));
                    }
                }

                @Override
                public void onErrorResponse(VolleyError volleyError) {

                }
            });
        }
        int sex = R.mipmap.boy_icon;
        if (bean.getData().getGender() == 1) {
            sex = R.mipmap.boy_icon;
        } else {
            sex = R.mipmap.girl_icon;
        }
        mGender.setImageResource(sex);
        VolleyTool.getImageLoader().get(Constants.IMAGE_HOST + bean.getData().getAvatar(), new ImageLoader.ImageListener() {
            @Override
            public void onResponse(ImageLoader.ImageContainer imageContainer, boolean b) {
                if (imageContainer.getBitmap() != null) {
                    mAvatar.setImageBitmap(BitmapUtils.toRoundBitmap(imageContainer.getBitmap(), 3, R.color.white));
                }
            }

            @Override
            public void onErrorResponse(VolleyError volleyError) {

            }
        });
        return view;
    }

    private void initHeadView(View view) {
        mGender = (ImageView) view.findViewById(R.id.gender);
        mAvatar = (ImageView) view.findViewById(R.id.avatar);
        mUserName = (TextView) view.findViewById(R.id.userName);
        mUserType = (TextView) view.findViewById(R.id.userType);
        mLevel = (TextView) view.findViewById(R.id.level);
        mGuanzhuCount = (TextView) view.findViewById(R.id.guanzhuCount);
        mFensiCount = (TextView) view.findViewById(R.id.fensiCount);
        mTangguoCount = (TextView) view.findViewById(R.id.tangguoCount);
        mAuth = (ImageView) view.findViewById(R.id.auth);
        ll_empty = (LinearLayout) view.findViewById(R.id.ll_empty);

        llHeadBg = (LinearLayout) view.findViewById(R.id.avtarLayout);
//        mGender = (ImageView) view.findViewById(R.id.gender);
//        mAvatar = (ImageView) view.findViewById(R.id.avatar);
//        mUserName = (TextView) view.findViewById(R.id.userName);
//        mUserType = (TextView) view.findViewById(R.id.userType);
//        mLevel = (TextView) view.findViewById(R.id.level);
//        mGuanzhuCount = (TextView) view.findViewById(R.id.guanzhuCount);
//        mFensiCount = (TextView) view.findViewById(R.id.fensiCount);
//        mTangguoCount = (TextView) view.findViewById(R.id.tangguoCount);
    }

    private void loadCommentNetworkData() {
        Map<String, String> params = new HashMap<>();
        params.put("acc_token", UserTools.getUser(this).getAcc_token());
        params.put("pn", currentPage + "");
        params.put("maxResults", maxResults + "");
        VolleyTool.get(this, Constants.MY_TOPIC_URL, params, this, Constants.MY_TOPIC, TopicBean.class);
    }

    private void initListener() {
        findViewById(R.id.imv_photo).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MyHomePageActivity.this, MyAlbumActivity.class);
                startActivity(intent);
            }
        });
        mListView.setLoadMoreListen(this);
        findViewById(R.id.iv_back).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        mShow.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent qaIntent = new Intent();
                qaIntent.putExtra("category", 4);
                qaIntent.setClass(MyHomePageActivity.this, PublishTopicActivity.class);
                startActivityForResult(qaIntent, 110);

            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode == RESULT_OK){
            String msg = data.getStringExtra("msg");
            try {
                JSONObject object = new JSONObject(msg);
                String obj = object.getJSONObject("data").toString();
                MLog.e(obj+"个人主页");
                Gson gson = new Gson();
                TopicBean.TopicResult topicResult = gson.fromJson(obj, TopicBean.TopicResult.class);
                adapter.getData().addFirst(topicResult);
                adapter.notifyDataSetChanged();
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

    }

    @Override
    public <T> void onResponse(T t, int requestCode) {
        if (requestCode == Constants.MY_TOPIC) {
            TopicBean bean = (TopicBean) t;
            if (bean.getCode() >= 0) {
                LinkedList<TopicBean.TopicResult> beans = bean.getData().getResults();
                if (currentPage == 1) {
                    adapter.getData().clear();
                    adapter.getData().addAll(0, beans);
                    if (beans.size() == 0) {
                        ll_empty.setVisibility(View.VISIBLE);
                    }
                    adapter.notifyDataSetChanged();
                } else {
                    if (beans.size() > 0) {
                        adapter.getData().addAll(beans);
                        adapter.notifyDataSetChanged();
                    } else {
                        if (results.size() > 10) {
                            showToast("已加载完所有");
                        }
                    }
                    mListView.onLoadComplete();
                }
            } else {
                showToast(bean.getMessage());
            }
        }

    }

    @Override
    public void onErrorResponse(VolleyError error, int requestCode) {

    }

    @Override
    public void loadMore() {
        currentPage = currentPage + 1;
        loadCommentNetworkData();
    }
}
